import axios from 'axios'
import { ElMessage } from 'element-plus'

// 用于标记是否正在刷新token
let isRefreshing = false
// 存储待重试的请求
let failedQueue = []

// 处理队列中的请求
const processQueue = (error, token = null) => {
  failedQueue.forEach(prom => {
    if (error) {
      prom.reject(error)
    } else {
      prom.resolve(token)
    }
  })

  failedQueue = []
}

const request = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 获取token的函数，支持从localStorage或Pinia获取
    const getToken = () => {
      // 优先从localStorage获取（保持兼容性）
      const token = localStorage.getItem('token')
      return token
    }
    
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code === 200) {
      return res
    } else {
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  error => {
    
    if (error.response?.status === 401) {
      console.log('检测到401状态码，尝试刷新token')

      const originalRequest = error.config

      // 如果已经在刷新token，将请求加入队列
      if (isRefreshing) {
        return new Promise((resolve, reject) => {
          failedQueue.push({ resolve, reject })
        }).then(token => {
          originalRequest.headers.Authorization = `Bearer ${token}`
          return axios(originalRequest)
        }).catch(err => {
          return Promise.reject(err)
        })
      }

      // 获取刷新token
      const refreshToken = localStorage.getItem('refreshToken')

      if (refreshToken && !originalRequest._retry) {
        originalRequest._retry = true
        isRefreshing = true

        // 动态导入刷新token的API
        return import('../api/auth.js').then(({ refreshToken: refreshTokenApi }) => {
          return refreshTokenApi(refreshToken)
        }).then(response => {
          const { accessToken, refreshToken: newRefreshToken } = response.data

          // 更新本地存储的token
          localStorage.setItem('token', accessToken)
          localStorage.setItem('refreshToken', newRefreshToken)

          // 更新默认请求头
          request.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`
          originalRequest.headers.Authorization = `Bearer ${accessToken}`

          // 处理队列中的请求
          processQueue(null, accessToken)

          // 重试原始请求
          return axios(originalRequest)
        }).catch(refreshError => {
          console.log('刷新token失败，跳转到登录页')

          // 处理队列中的请求
          processQueue(refreshError, null)

          // 清除登录状态
          localStorage.removeItem('token')
          localStorage.removeItem('refreshToken')
          localStorage.removeItem('userInfo')

          // 跳转到登录页（避免在登录页面时重复跳转）
          if (window.location.pathname !== '/login') {
            window.location.href = '/login'
          }

          return Promise.reject(refreshError)
        }).finally(() => {
          isRefreshing = false
        })
      } else {
        // 没有刷新token或已经重试过，直接跳转登录页
        console.log('没有刷新token或重试失败，跳转到登录页')
        localStorage.removeItem('token')
        localStorage.removeItem('refreshToken')
        localStorage.removeItem('userInfo')

        // 避免在登录页面时重复跳转
        if (window.location.pathname !== '/login') {
          window.location.href = '/login'
        }
        return Promise.reject(error)
      }
    }
    
    // 如果有响应数据，显示后端的错误信息
    const message = error.response?.data?.message || error.response?.data?.msg || error.message || '网络错误'
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export default request 